import { createContext, PropsWithChildren, useEffect, useMemo, useState } from "react";
import { useHidAutoConnect } from "../hooks/useHidAutoConnect";
import { Button, Empty, message, Modal } from "antd";
import { RaysDevice } from "./devices/rays";
import { MarigoldDevice } from "./devices/marigold";
import { HidDeviceInfo } from "../hooks/useHid";

interface ContextType extends ReturnType<typeof useHidAutoConnect> {
  currentStep: number;
  setCurrentStep: (step: number) => void;
  huihifi?: boolean;
}

export const Context = createContext<ContextType | undefined>(undefined)

export default function Provider({
  children,
}: PropsWithChildren<{
}>) {

  const [deviceInfo, setDeviceInfo] = useState<HidDeviceInfo | null>(null)
  const [device, setDevice] = useState<RaysDevice | MarigoldDevice | null>(null)
  const [currentStep, setCurrentStep] = useState<number>(0)
  const [isGraphPage, setIsGraphPage] = useState<boolean>(false)
  const [store, setStore] = useState<API.EQResult[]>([])
  const [eqs, setEqs] = useState<API.EQResult[]>([])

  const {
    isSupported,
    isConnecting,
    isAuthorizing,
    error,
    connectedDevices,
    requestDevice,
    connectDevice,
    disconnectDevice,
    tryAutoConnect,
    getDeviceId,
    sendData,
  } = useHidAutoConnect({
    autoConnect: true,
    debug: true,
    filters: [{vendorId: 13058}],
    onDeviceConnect: async (info, device) => {
      // save connected device
      setDeviceInfo({
        ...info,
        connected: true,
      })

      const deviceId = getDeviceId(device)
      const options = {
        sendData: (data: BufferSource, reportId: number) => sendData(deviceId, data, reportId, 2000, true),
        sendDataNoResp: (data: BufferSource, reportId: number) => sendData(deviceId, data, reportId, 2000, false),
      }

      try {
        if (info.productId === 0x011B) {
          const deviceInstance = new RaysDevice(options)
          setDevice(deviceInstance)
        }
        else if (info.productId === 0x011A) {
          const deviceInstance = new MarigoldDevice(options)
          setDevice(deviceInstance)
        }
      }
      catch (error) {
        console.error('Device initialization error:', error)
      }

      // set current step
      setCurrentStep(3)
    },
    onDeviceDisconnect: (_, manual) => {
      setIsGraphPage(false)
      setCurrentStep(0)
      // clearDevice()

      if (!manual) {
        // Store the current EQs for reconnection
        setStore(eqs)
        // clearEQ()
        message.error('设备已断开连接')
      }
      else {
        // Reset the EQs
        setStore([])
        // clearEQ()
        message.success('设备已成功断开连接')
      }
    },
    onError: () => {
      setCurrentStep(0)
    },
  })

  async function handleConnect() {
    if (!isSupported()) {
      Modal.info({
        title: '浏览器不支持',
        content: `您的浏览器不支持 WebHID API，请使用最新版的 <a
          href="https://www.google.com/chrome/"
            target="_blank"
            class="text-blue-500 transition-all hover:text-blue-600"
          >Chrome</a> 或 <a
            href="https://www.microsoft.com/edge/download"
            target="_blank"
            class="text-blue-500 transition-all hover:text-blue-600"
          >Edge</a> 浏览器。`,
        okText: '知道了',
      })
      return
    }

    if (currentStep === 3) {
      // handleContinue()
      return
    }

    try {
      // first step: request device
      setCurrentStep(1)
      const device = await requestDevice()
      if (!device) {
        throw new Error('未选择设备')
      }

      // second step: wait for authorization
      setCurrentStep(2)

      // third step: connect device
      const connected = await connectDevice(device)
      if (!connected) {
        throw new Error('设备连接失败')
      }
    }
    catch (error) {
      setCurrentStep(0)
      console.error('Connection failed:', error)
    }
  }

  useEffect(()=>{
    tryAutoConnect();
  },[])


  return <Context.Provider value={{
    isSupported,
    isConnecting,
    isAuthorizing,
    error,
    connectedDevices,
    requestDevice,
    connectDevice,
    disconnectDevice,
    getDeviceId,
    sendData,
    currentStep,
    setCurrentStep,
  }}>
    {!connectedDevices[0] ? <Empty description="请连接HUIHIFI耳机">
      <Button type="primary" onClick={() => {
        handleConnect();
      }}>
        连接HUIHIFI耳机
      </Button>
    </Empty> : children}
  </Context.Provider>
}
